<template>
  <div class="min-h-screen bg-gradient-to-br from-gray-50 via-blue-50 to-indigo-50">
    <!-- Background decorations -->
    <div class="absolute inset-0 overflow-hidden pointer-events-none">
      <div class="absolute -top-40 -right-40 w-80 h-80 bg-blue-200 rounded-full mix-blend-multiply filter blur-xl opacity-70 animate-blob"></div>
      <div class="absolute -bottom-40 -left-40 w-80 h-80 bg-purple-200 rounded-full mix-blend-multiply filter blur-xl opacity-70 animate-blob animation-delay-2000"></div>
      <div class="absolute top-40 left-40 w-80 h-80 bg-pink-200 rounded-full mix-blend-multiply filter blur-xl opacity-70 animate-blob animation-delay-4000"></div>
    </div>

    <!-- Main content area -->
    <div class="container mx-auto px-12 py-10 pt-32 relative z-10">
      <!-- Top: Back button & Title -->
      <div class="flex items-center justify-between mb-10">
        <div class="flex items-center gap-4">
          <el-button type="primary" link @click="goBack" class="text-gray-600 hover:text-gray-800 text-lg">
            <el-icon class="mr-2 text-xl"><ArrowLeft /></el-icon>
            返回班级详情
          </el-button>
          <h1 class="text-4xl font-bold text-gray-900">交作业</h1>
        </div>
        <div class="flex items-center gap-4">
          <el-button type="primary" size="large" @click="showSubmitDialog = true" class="rounded-full px-6">
            <el-icon class="mr-2"><Plus /></el-icon>
            提交作业
          </el-button>
        </div>
      </div>

      <!-- Stats cards -->
      <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
        <div class="bg-white rounded-2xl shadow-lg border border-gray-200 p-6 hover:shadow-xl transition-shadow duration-300">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-gray-600">总作业数</p>
              <p class="text-3xl font-bold text-gray-900">{{ homeworkStats.total }}</p>
            </div>
            <div class="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center">
              <el-icon class="text-2xl text-blue-600"><Document /></el-icon>
            </div>
          </div>
        </div>
        
        <div class="bg-white rounded-2xl shadow-lg border border-gray-200 p-6 hover:shadow-xl transition-shadow duration-300">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-gray-600">已完成</p>
              <p class="text-3xl font-bold text-green-600">{{ homeworkStats.completed }}</p>
            </div>
            <div class="w-12 h-12 bg-green-100 rounded-full flex items-center justify-center">
              <el-icon class="text-2xl text-green-600"><Check /></el-icon>
            </div>
          </div>
        </div>
        
        <div class="bg-white rounded-2xl shadow-lg border border-gray-200 p-6 hover:shadow-xl transition-shadow duration-300">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-gray-600">待提交</p>
              <p class="text-3xl font-bold text-orange-600">{{ homeworkStats.pending }}</p>
            </div>
            <div class="w-12 h-12 bg-orange-100 rounded-full flex items-center justify-center">
              <el-icon class="text-2xl text-orange-600"><Clock /></el-icon>
            </div>
          </div>
        </div>
        
        <div class="bg-white rounded-2xl shadow-lg border border-gray-200 p-6 hover:shadow-xl transition-shadow duration-300">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-gray-600">优秀作业</p>
              <p class="text-3xl font-bold text-purple-600">{{ homeworkStats.excellent }}</p>
            </div>
            <div class="w-12 h-12 bg-purple-100 rounded-full flex items-center justify-center">
              <el-icon class="text-2xl text-purple-600"><Star /></el-icon>
            </div>
          </div>
        </div>
      </div>

      <!-- Homework list -->
      <div class="bg-white rounded-3xl shadow-xl border border-gray-200 overflow-hidden">
        <div class="px-8 py-6 border-b border-gray-200 bg-gradient-to-r from-blue-50 to-indigo-50">
          <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
            <h2 class="text-2xl font-bold text-gray-900">作业列表</h2>
            <div class="flex items-center gap-4">
              <el-input
                v-model="searchText"
                placeholder="搜索作业..."
                class="w-64"
                :prefix-icon="Search"
                size="default"
              />
              <el-select v-model="statusFilter" placeholder="状态筛选" class="w-32" size="default">
                <el-option label="全部" value="" />
                <el-option label="待提交" value="pending" />
                <el-option label="已提交" value="submitted" />
                <el-option label="已批改" value="graded" />
              </el-select>
            </div>
          </div>
        </div>
        
        <div class="p-8">
          <div class="space-y-6">
            <div v-for="homework in filteredHomeworkList" :key="homework.id"
                 @click="viewHomeworkDetail(homework)"
                 class="group p-6 border-2 border-gray-100 rounded-2xl hover:border-blue-300 hover:bg-blue-50 transition-all duration-300 cursor-pointer">
              <div class="flex items-start justify-between">
                <div class="flex-1">
                  <div class="flex items-center gap-3 mb-3">
                    <h3 class="text-xl font-semibold text-gray-900 group-hover:text-blue-700 transition-colors">
                      {{ homework.title }}
                    </h3>
                    <span :class="getStatusClass(homework.status)" class="px-3 py-1 rounded-full text-sm font-medium">
                      {{ getStatusText(homework.status) }}
                    </span>
                  </div>
                  <p class="text-gray-600 mb-4">{{ homework.description }}</p>
                  <div class="flex items-center gap-6 text-sm text-gray-500">
                    <span class="flex items-center gap-2">
                      <el-icon><Calendar /></el-icon>
                      截止时间：{{ formatDate(homework.dueDate) }}
                    </span>
                    <span class="flex items-center gap-2">
                      <el-icon><User /></el-icon>
                      发布者：{{ homework.teacher }}
                    </span>
                    <span v-if="homework.score" class="flex items-center gap-2">
                      <el-icon><Star /></el-icon>
                      得分：{{ homework.score }}/{{ homework.maxScore }}
                    </span>
                  </div>
                </div>
                <div class="flex items-center gap-2">
                  <el-button type="primary" link size="small" @click.stop="downloadHomework(homework)">
                    <el-icon><Download /></el-icon>
                    下载
                  </el-button>
                  <el-button type="info" link size="small" @click.stop="viewHomeworkDetail(homework)">
                    <el-icon><ArrowRight /></el-icon>
                    查看详情
                  </el-button>
                </div>
              </div>
            </div>
            
            <!-- Empty state -->
            <div v-if="filteredHomeworkList.length === 0" class="text-center py-16">
              <div class="w-24 h-24 mx-auto mb-6 bg-gray-100 rounded-full flex items-center justify-center">
                <el-icon class="text-4xl text-gray-400"><Notebook /></el-icon>
              </div>
              <h3 class="text-xl font-medium text-gray-900 mb-2">暂无作业</h3>
              <p class="text-gray-500">当前没有需要完成的作业</p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Submit Homework Dialog -->
    <el-dialog v-model="showSubmitDialog" title="提交作业" width="600px" :close-on-click-modal="false">
      <el-form :model="submitForm" :rules="submitRules" ref="submitFormRef" label-width="100px">
        <el-form-item label="作业标题" prop="title">
          <el-input v-model="submitForm.title" placeholder="请输入作业标题" />
        </el-form-item>
        <el-form-item label="作业描述" prop="description">
          <el-input v-model="submitForm.description" type="textarea" :rows="4" placeholder="请输入作业描述" />
        </el-form-item>
        <el-form-item label="上传文件" prop="files">
          <el-upload
            v-model:file-list="submitForm.files"
            action="#"
            :auto-upload="false"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            multiple
            drag
          >
            <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持 PDF、Word、图片等格式，单个文件不超过 10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showSubmitDialog = false">取消</el-button>
          <el-button type="primary" @click="submitHomework">提交作业</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- Homework Detail Dialog -->
    <el-dialog v-model="showDetailDialog" title="作业详情" width="800px">
      <div v-if="selectedHomework" class="space-y-6">
        <div class="bg-gray-50 rounded-lg p-4">
          <h3 class="text-lg font-semibold text-gray-900 mb-2">{{ selectedHomework.title }}</h3>
          <p class="text-gray-600">{{ selectedHomework.description }}</p>
        </div>
        
        <div class="grid grid-cols-2 gap-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">发布者</label>
            <p class="text-gray-900">{{ selectedHomework.teacher }}</p>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">截止时间</label>
            <p class="text-gray-900">{{ formatDate(selectedHomework.dueDate) }}</p>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">状态</label>
            <span :class="getStatusClass(selectedHomework.status)" class="px-2 py-1 rounded text-sm">
              {{ getStatusText(selectedHomework.status) }}
            </span>
          </div>
          <div v-if="selectedHomework.score">
            <label class="block text-sm font-medium text-gray-700 mb-1">得分</label>
            <p class="text-gray-900">{{ selectedHomework.score }}/{{ selectedHomework.maxScore }}</p>
          </div>
        </div>
        
        <div v-if="selectedHomework.feedback">
          <label class="block text-sm font-medium text-gray-700 mb-2">教师评语</label>
          <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-3">
            <p class="text-gray-800">{{ selectedHomework.feedback }}</p>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { mockClassList } from '@/mock/classData'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  ArrowLeft, ArrowRight, Plus, Document, Check, Clock, Star, 
  Notebook, Search, UploadFilled, Download, Calendar, User 
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const classId = computed(() => Number(route.params.id))
const classInfo = computed(() => mockClassList.find(c => c.id === classId.value))

// 作业统计数据
const homeworkStats = ref({
  total: 12,
  completed: 8,
  pending: 3,
  excellent: 2
})

// 作业列表数据
const homeworkList = ref([
  {
    id: 1,
    title: 'Vue.js 基础语法练习',
    description: '完成Vue.js基础语法练习，包括数据绑定、事件处理、条件渲染等',
    status: 'submitted',
    dueDate: '2024-01-15',
    teacher: '张老师',
    score: 85,
    maxScore: 100,
    feedback: '代码结构清晰，但可以优化性能'
  },
  {
    id: 2,
    title: '组件化开发实践',
    description: '创建一个可复用的Vue组件，要求支持插槽和事件',
    status: 'graded',
    dueDate: '2024-01-10',
    teacher: '李老师',
    score: 92,
    maxScore: 100,
    feedback: '组件设计很好，代码规范'
  },
  {
    id: 3,
    title: '路由配置与导航',
    description: '配置Vue Router，实现页面间的导航和参数传递',
    status: 'pending',
    dueDate: '2024-01-20',
    teacher: '王老师'
  },
  {
    id: 4,
    title: '状态管理实践',
    description: '使用Pinia或Vuex实现状态管理，完成购物车功能',
    status: 'pending',
    dueDate: '2024-01-25',
    teacher: '陈老师'
  },
  {
    id: 5,
    title: 'API接口调用',
    description: '实现用户登录、注册、数据获取等API接口调用',
    status: 'submitted',
    dueDate: '2024-01-12',
    teacher: '刘老师',
    score: 88,
    maxScore: 100,
    feedback: '接口调用正确，错误处理需要完善'
  }
])

// 搜索和筛选
const searchText = ref('')
const statusFilter = ref('')

// 筛选后的作业列表
const filteredHomeworkList = computed(() => {
  let filtered = homeworkList.value
  
  if (searchText.value) {
    filtered = filtered.filter(hw => 
      hw.title.toLowerCase().includes(searchText.value.toLowerCase()) ||
      hw.description.toLowerCase().includes(searchText.value.toLowerCase())
    )
  }
  
  if (statusFilter.value) {
    filtered = filtered.filter(hw => hw.status === statusFilter.value)
  }
  
  return filtered
})

// 提交作业相关
const showSubmitDialog = ref(false)
const submitFormRef = ref()
const submitForm = ref({
  title: '',
  description: '',
  files: []
})

const submitRules = {
  title: [{ required: true, message: '请输入作业标题', trigger: 'blur' }],
  description: [{ required: true, message: '请输入作业描述', trigger: 'blur' }],
  files: [{ required: true, message: '请上传作业文件', trigger: 'change' }]
}

// 作业详情相关
const showDetailDialog = ref(false)
const selectedHomework = ref(null)

// 方法
const goBack = () => {
  router.back()
}

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN')
}

const getStatusText = (status) => {
  const statusMap = {
    pending: '待提交',
    submitted: '已提交',
    graded: '已批改'
  }
  return statusMap[status] || status
}

const getStatusClass = (status) => {
  const classMap = {
    pending: 'bg-orange-100 text-orange-800',
    submitted: 'bg-blue-100 text-blue-800',
    graded: 'bg-green-100 text-green-800'
  }
  return classMap[status] || 'bg-gray-100 text-gray-800'
}

const handleFileChange = (file) => {
  console.log('文件选择:', file)
}

const handleFileRemove = (file) => {
  console.log('文件移除:', file)
}

const submitHomework = async () => {
  try {
    await submitFormRef.value.validate()
    
    // 这里应该调用后端API提交作业
    ElMessage.success('作业提交成功！')
    showSubmitDialog.value = false
    
    // 重置表单
    submitForm.value = {
      title: '',
      description: '',
      files: []
    }
    
    // 刷新作业列表
    // loadHomeworkList()
    
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const viewHomeworkDetail = (homework) => {
  selectedHomework.value = homework
  showDetailDialog.value = true
}

const downloadHomework = (homework) => {
  ElMessage.info('下载功能由后端实现')
}

onMounted(() => {
  // 这里可以加载作业数据
  console.log('作业页面加载完成，班级ID:', classId.value)
})
</script>

<style scoped>
.animate-blob {
  animation: blob 7s infinite;
}

.animation-delay-2000 {
  animation-delay: 2s;
}

.animation-delay-4000 {
  animation-delay: 4s;
}

@keyframes blob {
  0% {
    transform: translate(0px, 0px) scale(1);
  }
  33% {
    transform: translate(30px, -50px) scale(1.1);
  }
  66% {
    transform: translate(-20px, 20px) scale(0.9);
  }
  100% {
    transform: translate(0px, 0px) scale(1);
  }
}

/* 自定义上传组件样式 */
:deep(.el-upload-dragger) {
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  background-color: #fafafa;
  transition: all 0.3s;
}

:deep(.el-upload-dragger:hover) {
  border-color: #409eff;
  background-color: #f0f9ff;
}

:deep(.el-upload-dragger .el-icon--upload) {
  font-size: 48px;
  color: #c0c4cc;
  margin-bottom: 16px;
}

:deep(.el-upload-dragger:hover .el-icon--upload) {
  color: #409eff;
}

/* 自定义滚动条 */
::-webkit-scrollbar {
  width: 8px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>
